from PyQt4.QtGui import *
from PyQt4.QtCore import *

from core.base import ServerComponent 
from ui.models import NIModel, SelectionModel, DataItem
from core import cmds

class NodeListWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        
        self.list_view = QTreeView(self)
        self.list_view.setModel(NIModel())
        self.list_view.setSelectionModel(SelectionModel(self.list_view.model()))
        self.list_view.setSelectionBehavior(QAbstractItemView.SelectItems)
        self.list_view.setContextMenuPolicy(Qt.CustomContextMenu)
        self.list_view.setAlternatingRowColors(True)
        
        self.list_view.setDragEnabled(True)
        self.list_view.setDragDropMode(QAbstractItemView.DragDrop)
        self.list_view.setAcceptDrops(True)
        self.list_view.setDropIndicatorShown(True)
        #self.list_view.setDragDropMode(QAbstractItemView.DragOnly)
        #self.list_view.setDragEnabled(True)
        
        self.name_field = QLineEdit(self)
        self.create_button = QToolButton(self)
        
        bottom_layout = QHBoxLayout()
        for widget in [self.name_field, self.create_button]:
            bottom_layout.addWidget(widget)
        
        main_layout = QVBoxLayout()
        main_layout.addWidget(self.list_view)
        main_layout.addLayout(bottom_layout)
        self.setLayout(main_layout)
        
        self.name_field.setText("NameOfNewComponent")
        
        self.create_comp_act = QAction(self)
        self.create_comp_act.setText("+")
        self.connect(self.create_comp_act, SIGNAL("triggered()"), self.create_comp)
        self.create_button.setDefaultAction(self.create_comp_act)
        
    def create_comp(self):
        name = str(self.name_field.text())
        cmds.new_type(name)
        
class NodeView(ni.View):
    widget = NodeListWidget
    
    def update_widget(self, widget):
        widget.list_view.model().clear()
        nodes = list(cmds.types(ni.Node))
        server_nodes = list(cmds.types(ServerComponent))
        views = list(cmds.types(ni.View))
        
        parent = widget.list_view.model().invisibleRootItem()
        for item in nodes + server_nodes + views:
            data = DataItem(item)
            
            parent.setChild(parent.rowCount(), 0, data)
        
        #widget.list_view.model().add(nodes + server_nodes + views)
        
    
    
    